﻿using D.B.Data.API.Filter;
using D.B.Data.Common;
using D.B.Data.Infrastructuse;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Reflection;
using System.Text;

namespace D.B.Data.API.Extensions
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class ServiceCollectionExtensions
    {


        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

            services.AddScoped<JwtTools>();

            return services;    
        }


        /// <summary>
        /// 打印SQL 在控制台
        /// </summary>
        /// <typeparam name="DataDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<DataDbContext>(this IServiceCollection services, string? connectionString,bool enableSqlLog) where DataDbContext : DbContext
        {
            return services.AddDbContext<DataDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                }).EnableSensitiveDataLogging();
                if(enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }


            });
        }



        public static void AddJWT(this IServiceCollection services, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecretKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["JwtSettings:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["JwtSettings:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }
    }
}
